package top.lywivan.netty.handler.clinet;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import top.lywivan.netty.pojo.UserInfo;

import java.util.concurrent.TimeUnit;

/**
 * @author :lyw.ivan
 * @date :Created in 2022/8/14
 * @description : 客户端写事件空闲检测，当空闲一定时间，主动发送心跳，避免被服务端断开连接
 * @version: 1.0
 */
public class ClientWriterIdleHandler extends IdleStateHandler {
    public ClientWriterIdleHandler(int readerIdleTimeSeconds, int writerIdleTimeSeconds, int allIdleTimeSeconds) {
        super(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds, TimeUnit.SECONDS);
    }

    @Override
    protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
        //当时间为写空闲时，发送keepalive的心跳消息
        if(evt==IdleStateEvent.FIRST_WRITER_IDLE_STATE_EVENT){
            //发送消息
            UserInfo userInfo=new UserInfo();
            userInfo.setName("keepalive");
            ctx.channel().writeAndFlush(userInfo);
        }
        super.channelIdle(ctx, evt);
    }
}
